<template>
  <div class="user-container">
   
    <el-card class="main-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="mr-5"><List /></el-icon>
            <span class="title">用户管理</span>
          </div>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>添加用户
          </el-button>
        </div>
      </template>

      <el-table
        :data="userList"
        style="width: 100%"
        v-loading="loading"
        :empty-text="loading ? '加载中...' : '暂无数据'"
        border
        stripe
        highlight-current-row
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="role" label="角色" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.role === 1 ? 'danger' : 'success'" effect="plain">
              {{ row.role === 1 ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="280" align="center">
          <template #default="{ row }">
            <el-button-group>
              <el-button link type="primary" @click="handleEdit(row)">
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button link type="primary" @click="handleResetPassword(row)">
                <el-icon><Key /></el-icon>重置密码
              </el-button>
              <el-button
                link
                :type="row.status === 1 ? 'danger' : 'success'"
                @click="handleToggleStatus(row)"
              >
                <el-icon>
                  <component :is="row.status === 1 ? 'Lock' : 'Unlock'" />
                </el-icon>
                {{ row.status === 1 ? '禁用' : '启用' }}
              </el-button>
              <el-button link type="danger" @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-if="total > 0"
        class="pagination"
        background
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 用户编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加用户' : '编辑用户'"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="userForm"
        :rules="rules"
        label-width="80px"
        status-icon
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" :disabled="dialogType === 'edit'" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="userForm.password" type="password" show-password />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色" style="width: 100%">
            <el-option label="管理员" :value="1" />
            <el-option label="普通用户" :value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import request from '@/utils/request'
import {
  User,
  UserFilled,
  Avatar,
  Connection,
  Plus,
  Edit,
  Key,
  Lock,
  Unlock,
  Delete,
  List
} from '@element-plus/icons-vue'

// 所有的 ref 声明要在最前面
const userList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref()
const loading = ref(false)
const userForm = ref({
  username: '',
  password: '',
  role: 2
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleString()
}

const loadData = async () => {
  try {
    loading.value = true
    const res = await request({
      url: '/api/user/list',
      method: 'get',
      params: {
        page: currentPage.value,
        size: pageSize.value
      }
    })
    
    if (res.code === 200) {
      userList.value = res.data.records
      total.value = res.data.total
    }
  } catch (error) {
    console.error('加载用户列表失败:', error)
    ElMessage.error('加载用户列表失败')
  } finally {
    loading.value = false
  }
}

const handleAdd = () => {
  dialogType.value = 'add'
  userForm.value = {
    username: '',
    password: '',
    role: 2
  }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  userForm.value = {
    id: row.id,
    username: row.username,
    role: row.role
  }
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    const method = dialogType.value === 'add' ? 'post' : 'put'
    const url = dialogType.value === 'add' ? '/api/user' : `/api/user/${userForm.value.id}`
    const res = await request[method](url, userForm.value)

    if (res.code === 200) {
      ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
      dialogVisible.value = false
      loadData()
    }
  } catch (error) {
    console.error('提交失败:', error)
  }
}

const handleResetPassword = async (row) => {
  try {
    await ElMessageBox.confirm('确定要重置该用户的密码吗？', '提示', {
      type: 'warning'
    })
    const res = await request.put(`/api/user/${row.id}/password/reset`)
    if (res.code === 200) {
      ElMessage.success('密码重置成功')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重置密码失败:', error)
    }
  }
}

const handleToggleStatus = async (row) => {
  try {
    const action = row.status === 1 ? 'ban' : 'unban'
    const confirmText = row.status === 1 ? '禁用' : '启用'
    await ElMessageBox.confirm(`确定要${confirmText}该用户吗？`, '提示', {
      type: 'warning'
    })
    const res = await request.put(`/api/user/${row.id}/${action}`)
    if (res.code === 200) {
      ElMessage.success(`${confirmText}成功`)
      loadData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
    }
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
      type: 'warning'
    })
    const res = await request.delete(`/api/user/${row.id}`)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      loadData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  loadData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadData()
}

// 添加统计数据
const adminCount = computed(() => userList.value.filter(user => user.role === 1).length)
const normalUserCount = computed(() => userList.value.filter(user => user.role === 2).length)
const onlineCount = computed(() => userList.value.filter(user => user.status === 1).length)

// 监听分页变化
watch([currentPage, pageSize], () => {
  loadData()
})

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.user-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 60px);
}

.statistics {
  margin-bottom: 20px;
}

.box-card {
  height: 140px;
  transition: all 0.3s;
  border: none;
}

.box-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  color: #606266;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-icon {
  font-size: 20px;
  color: #409eff;
}

.card-content {
  text-align: center;
  padding: 10px 0;
}

.card-value {
  font-size: 36px;
  font-weight: bold;
  color: #409eff;
  line-height: 1.2;
  margin-bottom: 5px;
}

.card-value.admin {
  color: #f56c6c;
}

.card-value.normal {
  color: #67c23a;
}

.card-value.online {
  color: #e6a23c;
}

.card-label {
  font-size: 14px;
  color: #909399;
}

.main-card {
  background-color: #fff;
  border-radius: 8px;
  border: none;
}

.main-card .title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.mr-5 {
  margin-right: 5px;
}

.el-table {
  margin: 15px 0;
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-button-group) .el-button--primary {
  background-color: transparent;
  border: none;
  box-shadow: none;
  padding: 4px 8px;
}

:deep(.el-button-group) .el-button--primary:hover {
  color: #409eff;
  background-color: #ecf5ff;
}

:deep(.el-button-group) .el-button--danger:hover {
  color: #f56c6c;
  background-color: #fef0f0;
}

:deep(.el-tag) {
  border-radius: 4px;
  padding: 0 10px;
  height: 24px;
  line-height: 22px;
}

:deep(.el-dialog) {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}

:deep(.el-dialog__header) {
  margin-right: 0;
  border-bottom: 1px solid #ebeef5;
  padding: 20px;
  font-weight: 600;
}

:deep(.el-dialog__body) {
  padding: 30px 20px;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #ebeef5;
  padding: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
}
</style>
